<?php
/**
 * 资讯列表
 * User: 江玉婵（QQ:1129901500)
 * Date: 2017/7/7
 * Time: 10:28
 */
namespace app\admin\controller;

use think\Controller;
use app\admin\model\News as News_mod;
use think\Config;
use think\Session;

class News extends Base{

    //这个方法没执行
    public function _initialize()
    {
        //需要调用`Model`的`initialize`方法
        parent::_initialize();
        //TODO:自定义的初始化
        $this->mod = new News_mod();
        $this->assign('title','资讯列表');
    }

    public function index() {

        $kw = trim ($this->request->param('kw'));
        $kw_cate = trim ($this->request->param('kw_cate'));

        if (! empty ( $kw_cate ) && $kw_cate != 'all') { $where['cate_id'] = $kw_cate; }
        if (! empty ( $kw )) { $where['t.title|t.keyword'] = ['like',"%$kw%"]; }
        $where['t.is_work'] = 1;
        $field = "t.id,t.title,t.keyword,t.cate_id,t.uadmin,t.utime,a.name uadmin,c.name cate_name";
        $order = ['t.id' => 'desc'];
        $join = [['admin a','a.id = t.uadmin','left'],['news_cate c','c.id = t.cate_id','left']];

        $list = $this->mod->field($field)->where($where)->order($order)->alias('t')->join($join)->paginate(10);

        $this->assign ( ['list'=>$list, 'kw'=>$kw, 'kw_cate'=>$kw_cate]);
        unset($list);
        return view();
    }

    public function edit() {
        if ($this->request->isPost()) {
            $data = $this->request->param();
            $data['utime'] = date('Y-m-d H:i:s');
            $data['uadmin'] = $this->session_id;
            if ( !isset($data['id']) ) {
                $data['ctime'] = date('Y-m-d H:i:s');
                $data['cadmin'] = $this->session_id;
                $this->mod->data($data)->save();
            } else {
                $where['id'] = $data['id'];
                unset($data['id']);
                $this->mod->save($data,$where);
            }
            $this->success('保存成功','News/index');
        } else {
            $cate = action('NewsCate/getInfo'); // 顶级分类

            $id = $this->request->param('id');
            $where['is_work'] = 1;
            $order['id'] = 'desc';
            if ($id) {
                $where['id'] = $id;
                $row = $this->mod->where($where)->order($order)->find();
                unset($where['id']);

                $this->assign(['row'=>$row, 'cate' => $cate]);
                return view();
            } else {
                $this->assign(['cate' => $cate]);
                return view('add');
            }
        }
    }
}
